
<template>
    <div class="product-analysis-container">
      <!-- 时间范围筛选 -->
      <div class="filter-section">
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button label="monthly">每月</el-radio-button>
          <el-radio-button label="quarterly">每季度</el-radio-button>
        </el-radio-group>
   
        <el-date-picker 
          v-model="selectedMonth"
          type="month"
          placeholder="选择月份"
          format="YYYY年MM月"
          value-format="YYYYMM"
          @change="handleDateChange"
          :picker-options="monthPickerOptions"
        />
      </div>
   
      <!-- 产品图表展示区 -->
      <div class="chart-area">
        <div class="chart-wrapper">
          <div class="chart-header">
            <h3>产品销售额分析</h3>
            <el-tooltip content="显示各产品销售额对比" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div ref="productChart" class="chart-content" v-loading="loading"></div>
        </div>
      </div>
   
      <!-- 产品数据表格 -->
      <div class="data-table">
        <el-table :data="productTableData" border stripe height="500">
          <el-table-column prop="productName" label="产品名称" width="180" fixed />
          <el-table-column prop="price" label="单价(元)" width="120" align="right">
            <template #default="{ row }">
              {{ formatCurrency(row.price)  }}
            </template>
          </el-table-column>
          <el-table-column prop="salesCount" label="销售数量" width="120" align="center" />
          <el-table-column prop="totalAmount" label="总金额(元)" width="150" align="right">
            <template #default="{ row }">
              {{ formatCurrency(row.totalAmount)  }}
            </template>
          </el-table-column>
          <el-table-column label="环比变化" width="150" align="center">
            <template #default="{ row }">
              <span :class="getChangeClass(row.monthlyChange)"> 
                {{ row.monthlyChange  !== null ? `${row.monthlyChange}%`  : '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="showProductDetail(row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </template>
   
  <script>
  import * as echarts from 'echarts';
import { debounce } from 'lodash';
  import { getProductSalesAPI } from '@/api/api';
  import dayjs from 'dayjs';
  import { QuestionFilled } from '@element-plus/icons-vue';
   
  export default {
    name: 'ProductAnalysis',
    components: { QuestionFilled },
    data() {
      return {
        timeRange: 'monthly',
        selectedMonth: dayjs().format('YYYYMM'),
        loading: false,
        productChart: null,
        productData: [],
        colorPalette: [
          '#5470C6', '#91CC75', '#FAC858', '#EE6666', 
          '#73C0DE', '#3BA272', '#FC8452', '#9A60B4',
          '#EA7CCC', '#FF9F7F', '#8399A7', '#B6A1DE'
        ]
      };
    },
    computed: {
      monthPickerOptions() {
        return {
          disabledDate: (time) => {
            return dayjs(time).isAfter(dayjs(), 'month');
          }
        };
      },
      productTableData() {
        return this.productData.map(product  => ({
          productId: product.pid, 
          productName: product.name, 
          price: product.price, 
          salesCount: product.salesCount, 
          totalAmount: product.totalAmount, 
          monthlyChange: product.monthlyChange  
        }));
      }
    },
    mounted() {
      this.initChart(); 
      this.fetchData(); 
      window.addEventListener('resize',  this.handleResize); 
    },
    beforeUnmount() {
      window.removeEventListener('resize',  this.handleResize); 
      this.productChart?.dispose(); 
    },
    methods: {
      initChart() {
        this.productChart  = echarts.init(this.$refs.productChart); 
      },
      
      async fetchData() {
        this.loading  = true;
        try {
          const params = {
            month: this.selectedMonth, 
            timeRange: this.timeRange 
          };
          
          const response = await getProductSalesAPI(params);
          this.productData  = response.data  || [];
          
          if (this.productData.length  > 0) {
            this.renderProductChart(); 
          } else {
            this.renderEmptyChart();  
          }
        } catch (error) {
          console.error(' 获取产品数据失败:', error);
          this.$message.error(' 获取产品数据失败');
          this.renderEmptyChart(); 
        } finally {
          this.loading  = false;
        }
      },
      
      renderProductChart() {
        const sortedData = [...this.productData].sort((a,  b) => b.totalAmount  - a.totalAmount); 
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: params => {
              let result = params[0].name + '<br/>';
              params.forEach(item  => {
                const data = sortedData[item.dataIndex];
                result += `
                  <div style="display:flex;align-items:center;margin:5px 0">
                    <span style="display:inline-block;width:10px;height:10px;background:${item.color};margin-right:5px"></span> 
                    ${item.seriesName}:  ${this.formatCurrency(data.totalAmount)}<br/> 
                    <small>销量: ${data.salesCount} 件</small>
                  </div>
                `;
              });
              return result;
            }
          },
          legend: {
            data: sortedData.map(p  => p.name), 
            type: 'scroll',
            bottom: 0
          },
          xAxis: {
            type: 'category',
            data: sortedData.map(p  => p.name), 
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value',
            name: '销售额(元)',
            axisLabel: {
              formatter: value => value >= 10000 ? `${(value/10000).toFixed(1)}万` : value 
            }
          },
          series: [{
            name: '销售额',
            type: 'bar',
            barWidth: '60%',
            data: sortedData.map((product,  index) => ({
              value: product.totalAmount, 
              itemStyle: {
                color: this.colorPalette[index  % this.colorPalette.length] 
              }
            })),
            label: {
              show: true,
              position: 'top',
              formatter: params => {
                const value = params.value; 
                return value >= 10000 
                  ? `${(value/10000).toFixed(1)}万` 
                  : value.toLocaleString(); 
              }
            }
          }],
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '5%',
            containLabel: true 
          }
        };
        
        this.productChart.setOption(option,  true);
      },
      
      renderEmptyChart() {
        const option = {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center',
            textStyle: { color: '#999' }
          },
          xAxis: { show: false },
          yAxis: { show: false }
        };
        this.productChart.setOption(option,  true);
      },
      
      handleResize: debounce(function() {
        this.productChart?.resize(); 
      }, 300),
      
      handleTimeRangeChange() {
        this.fetchData(); 
      },
      
      handleDateChange() {
        this.fetchData(); 
      },
      
      formatCurrency(value) {
        if (value === null || value === undefined) return '-';
        return new Intl.NumberFormat('zh-CN', {
          style: 'decimal',
          minimumFractionDigits: 2,
          maximumFractionDigits: 2 
        }).format(value);
      },
      
      getChangeClass(value) {
        if (value === null) return '';
        const num = parseFloat(value);
        if (num > 0) return 'positive-change';
        if (num < 0) return 'negative-change';
        return '';
      },
      
      showProductDetail(product) {
        this.$message.info(` 查看产品 ${product.productName}  的详细数据`);
        // 这里可以打开产品详情弹窗或跳转到详情页 
      }
    }
  };
  </script>
   
  <style lang="scss" scoped>
  .product-analysis-container {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
   
  .filter-section {
    background: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    
    .el-radio-group {
      margin-right: 20px;
    }
  }
   
  .chart-area {
    margin-bottom: 20px;
  }
   
  .chart-wrapper {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
   
    .chart-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
   
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: bold;
      }
   
      .el-icon {
        margin-left: 8px;
        color: #909399;
        cursor: pointer;
      }
    }
   
    .chart-content {
      height: 500px;
      width: 100%;
    }
  }
   
  .data-table {
    flex: 1;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
   
    :deep(.el-table) {
      .positive-change {
        color: #f56c6c;
        font-weight: bold;
      }
   
      .negative-change {
        color: #67c23a;
        font-weight: bold;
      }
    }
  }
  </style>